
package com.dave.gd.common.util.xml;

import java.util.Iterator;

import org.dom4j.DocumentException;
import org.dom4j.Element;

/**
 * 错误信息工具类
 * 
 * 
 * 
 */
public class XmlErrorUtil  {
	public static final String ELEMENT_LOSE = "cvc-complex-type.2.4.a";
	public static final String ELEMENT_REQUIRED_TEXT_LENGTH = "cvc-length-valid";
	public static final String ELEMENT_REQUIRED_TEXT_MINLENGTH = "cvc-minLength-valid";
	public static final String ELEMENT_OPPTIONAL_TEXT_DATATYPE = "cvc-datatype-valid.1.2.1";
	public static final String ELEMENT_TEXT_VALID = "cvc-type.3.1.3";
	public static final String ELEMENT_WITH_ATTRIBUTE_LENGTH = "cvc-complex-type.2.2";
	public static final String ELEMENT_REQUIRED_ATTRIBUTE_LOSE = "cvc-complex-type.4";
	public static final String ELEMENT_CHILDREN_LOSE = "cvc-complex-type.2.4.b";
	public static final String ELEMENT_ATTRIBUTE_UNIT = "cvc-complex-type.3.1";
	public static final String ELEMENT_ENUMERATION = "cvc-enumeration-valid";
	public static final String ELEMENT_REQUIERD_ATTRIBUTE_VALUE_LOSE = "cvc-pattern-valid";
	public static final String ELEMENT_OPTIONAL_ATTRIBUTE_VALUE_LOSE = "cvc-attribute.3";
	public static final String SINGLE_QUOTE = "\'";

	/**
	 * 获取XSD校验的错误信息
	 * 
	 * @param errors
	 *            XSD校验错误信息(Element)
	 * @return 错误信息字符串
	 */
	public static String getValidateErrorMsg(Element errors) {
		StringBuffer errMsg = new StringBuffer();

		for (@SuppressWarnings("unchecked")
		Iterator<Element> iter = errors.elementIterator(); iter.hasNext();) {
			Element childElement = iter.next();
			String childMessage = childElement.getText();
			// System.out.println(childMessage);

			if (childMessage.contains(ELEMENT_LOSE)) {
				String realMessage = validateElementLose(childMessage);
				errMsg.append("缺少<" + realMessage + ">节点!");
			} else if (childMessage.contains(ELEMENT_REQUIRED_TEXT_LENGTH)
					|| childMessage.contains(ELEMENT_REQUIRED_TEXT_MINLENGTH)) {
				Element element = iter.next();
				String secondLevelMessage = element.getText();

				// System.out.println(secondLevelMessage);

				if (secondLevelMessage.contains(ELEMENT_TEXT_VALID)) {
					String realMessage = validateElementTextLength(secondLevelMessage);
					errMsg.append("<" + realMessage + ">的长度不符合!");
				} else if (secondLevelMessage
						.contains(ELEMENT_WITH_ATTRIBUTE_LENGTH)) {
					String realMessage = validateComplexTypeElementWithAttribute(secondLevelMessage);
					errMsg.append("<" + realMessage + ">的长度不符合!");
				}
			} else if (childMessage.contains(ELEMENT_OPPTIONAL_TEXT_DATATYPE)) {
				String chooseTag = validateOpptionalElementText(childMessage);
				Element element = iter.next();
				String secondLevelMessage = element.getText();
				if (secondLevelMessage.contains(ELEMENT_TEXT_VALID)) {
					if ("\'\'".equals(chooseTag)) {
						String tagName = validateElementTextLength(secondLevelMessage);
						errMsg.append("<" + tagName + ">的长度不符合!");
					} else if (!"".equals(chooseTag)) {
						String tagName = validateElementTextLength(secondLevelMessage);
						int m = childMessage.lastIndexOf("for");
						int n = childMessage.lastIndexOf(SINGLE_QUOTE);
						String typeName = childMessage.substring(m + 5, n);
						errMsg.append("<" + tagName + ">的类型应该为：" + typeName
								+ "!");
					}
				} else if (secondLevelMessage
						.contains(ELEMENT_WITH_ATTRIBUTE_LENGTH)) {
					String realMessage = validateElementWithAttribute(secondLevelMessage);
					errMsg.append("<" + realMessage + ">带有属性，但长度或者类型不符合!");
				} else if (secondLevelMessage
						.contains(ELEMENT_OPTIONAL_ATTRIBUTE_VALUE_LOSE)) {
					String realMessage[] = validateAttributeValue(secondLevelMessage);
					errMsg.append("<" + realMessage[1] + ">的\'"
							+ realMessage[0] + "\'属性值不符合!");
				}
			} else if (childMessage.contains(ELEMENT_REQUIRED_ATTRIBUTE_LOSE)) {
				String[] realMessage = validateRequiredElementAttributeLose(childMessage);
				errMsg.append("<" + realMessage[1] + ">节点上缺少" + realMessage[0]
						+ "属性!");
			} else if (childMessage.contains(ELEMENT_CHILDREN_LOSE)) {
				String[] realMessage = validateElementWithChild(childMessage);
				errMsg.append("<" + realMessage[0] + ">节点上缺少" + realMessage[1]
						+ "子节点!");
			} else if (childMessage.contains(ELEMENT_ATTRIBUTE_UNIT)) {
				String[] realMessage = validateElementAttributeUnit(childMessage);
				errMsg.append("<" + realMessage[1] + ">的" + realMessage[0]
						+ "属性值应该为：" + realMessage[2] + "!");
			} else if (childMessage.contains(ELEMENT_ENUMERATION)) {
				String enumeration = validateEnumeration(childMessage);
				Element element = iter.next();
				String secondLevelMessage = element.getText();
				String[] realMessage = validateAttributeValue(secondLevelMessage);
				errMsg.append("<" + realMessage[1] + ">的属性" + realMessage[0]
						+ "只能在[" + enumeration + "]里面选择!");
			} else if (childMessage
					.contains(ELEMENT_REQUIERD_ATTRIBUTE_VALUE_LOSE)) {
				Element element = iter.next();
				String secondLevelMessage = element.getText();
				String realMessage[] = validateAttributeValue(secondLevelMessage);
				errMsg.append("<" + realMessage[1] + ">的" + realMessage[0]
						+ "属性值不符合!");
			}
		}
		// System.out.println(errMsg);
		if (errMsg.length() > 0) {
			return errMsg.toString();
		}

		return errors.getStringValue();
	}

	/**
	 * @param message
	 *            传过来的某一个元素的文本信息
	 * @return 返回元素名称（最后一个"{"+1，最后一个"'"-1）
	 * @throws DocumentException
	 */
	private static String validateElementLose(String message) {
		// \u007B表示转义的左大括号
		int i = message.lastIndexOf("\u007B");
		int j = message.lastIndexOf(SINGLE_QUOTE);
		return message.substring(i + 1, j - 1);
	}

	/**
	 * @param message
	 *            传过来的某一个元素的文本信息
	 * @return 返回元素名称(最后一个"element"+9,最后一个"'")
	 */
	private static String validateElementTextLength(String message) {
		int i = message.lastIndexOf("element");
		int j = message.lastIndexOf(SINGLE_QUOTE);
		String realMessage = message.substring(i + 9, j);

		return realMessage;
	}

	/**
	 * @param message
	 *            传过来的某一个元素的文本信息
	 * @return 返回一个字符串，''表示是元素的文本长度不对，!''表示是元素的文本类型不对（第一个"'"，第一个"is"-1）
	 */
	private static String validateOpptionalElementText(String message) {
		int i = message.indexOf(SINGLE_QUOTE);
		int j = message.indexOf("is");
		String realMessage = message.substring(i, j - 1);

		return realMessage;
	}

	/**
	 * @param message
	 *            传过来的某一个元素的文本信息
	 * @return 返回元素名称（第一个"'"+1，第一个"must"-2）
	 */
	private static String validateElementWithAttribute(String message) {
		int i = message.indexOf(SINGLE_QUOTE);
		int j = message.indexOf("must");
		String realMessage = message.substring(i + 1, j - 2);

		return realMessage;
	}

	/**
	 * @param message
	 *            传过来的某一个元素的文本信息
	 * @return 
	 *         返回一个数组，该数组有两个字符串对象，分别是元素名称（第一个"element"+9,最后一个"'"）和元素的属性名称（第一个"'"+
	 *         1,第一个"must"-2）
	 */
	private static String[] validateRequiredElementAttributeLose(String message) {
		int i = message.indexOf(SINGLE_QUOTE);
		int j = message.indexOf("must");
		String attributeMessage = message.substring(i + 1, j - 2);

		int m = message.indexOf("element");
		int n = message.lastIndexOf(SINGLE_QUOTE);
		String elementMessage = message.substring(m + 9, n);
		String[] realMessage = new String[] { attributeMessage, elementMessage };

		return realMessage;
	}

	/**
	 * @param message
	 *            传过来的某一个元素的文本信息
	 * @return 
	 *         返回一个数组，该数组有两个字符串对象，分别是元素名称（第一个"'"+1，第一个"is"-2）和该元素的子元素名称（第一个"{"+1，
	 *         最后一个"'"-1）
	 */
	private static String[] validateElementWithChild(String message) {
		int i = message.indexOf(SINGLE_QUOTE);
		int j = message.indexOf("is");
		String parentMessage = message.substring(i + 1, j - 2);

		int m = message.indexOf("\u007B");
		int n = message.lastIndexOf(SINGLE_QUOTE);
		String chlidMessage = message.substring(m + 1, n - 1);

		String[] realMessage = new String[] { parentMessage, chlidMessage };

		return realMessage;
	}

	private static String validateComplexTypeElementWithAttribute(String message) {
		int i = message.indexOf(SINGLE_QUOTE);
		int j = message.indexOf("must");

		return message.substring(i + 1, j - 2);
	}

	private static String[] validateElementAttributeUnit(String message) {
		int i = message.indexOf("attribute");
		int j = message.indexOf("element");
		String attributeName = message.substring(i + 11, j - 5);

		int n = message.indexOf("is");
		String elementName = message.substring(j + 9, n - 2);

		int k = message.lastIndexOf("of");
		int l = message.lastIndexOf(SINGLE_QUOTE);
		String unit = message.substring(k + 4, l);

		String[] realMessage = new String[] { attributeName, elementName, unit };

		return realMessage;
	}

	private static String validateEnumeration(String message) {
		// 左方括号
		int i = message.indexOf("\u005B");
		int j = message.indexOf("\u005D");
		String realMessage = message.substring(i + 1, j);
		return realMessage;
	}

	private static String[] validateAttributeValue(String message) {
		int i = message.lastIndexOf("attribute");
		int j = message.indexOf("element");
		String attributeName = message.substring(i + 11, j - 5);

		int n = message.indexOf("is");
		String elementName = message.substring(j + 9, n - 2);
		String[] realMessage = new String[] { attributeName, elementName };
		return realMessage;
	}

}
